#include "CommonDefines.h"

#include "bOSMutex.h"
using namespace bOS::Core;

#include "bOSSynchronizationException.h"
using namespace bOS::Exception;


Mutex::Mutex( String Name )
{
	setName(Name);

    m_hMtx = CreateMutex( NULL, FALSE, Name.c_str() );

    if ( m_hMtx == NULL ) 
	{
        throw SynchronizationException();
	}
}

Mutex::~Mutex()
{
    if ( m_hMtx != NULL )
	{
        CloseHandle( m_hMtx ); 
	}
}

void Mutex::lock()
{
    DWORD nResult = WaitForSingleObject( m_hMtx, INFINITE ); 
    if (nResult == WAIT_FAILED)
	{
        throw SynchronizationException();
	}
}

void Mutex::unlock()
{
    BOOL bResult = ReleaseMutex( m_hMtx );
    if ( !bResult )
	{
        throw SynchronizationException();
	}
}

bool Mutex::tryLock()
{
    DWORD nResult = WaitForSingleObject( m_hMtx, 0 ); 
    switch ( nResult )
    {
    case WAIT_OBJECT_0:
	    return true;
    case WAIT_TIMEOUT:
	    return false;
    default:
	    throw SynchronizationException();
    }
}

String Mutex::getName() 
{ 
    return sName;
}

void Mutex::setName( String Name )
{
    sName = Name;
}


